package com.jt.interceptor;

import com.jt.pojo.User;
import com.jt.util.CookieUtil;
import com.jt.util.ObjectMapperUtil;
import com.jt.util.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import redis.clients.jedis.JedisCluster;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Cx
 * @stage JT Of Fourth stage
 * @creat 2020-12-17 9:39
 */
@Component
public class UserInterceptor implements HandlerInterceptor {

    private static final String JT_TICKET = "JT_TICKET";

    @Autowired
    private JedisCluster jedisCluster;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        // 校验cookie中有无数据
        Cookie cookie = CookieUtil.getCookie(request, JT_TICKET);
        // 校验cookie是否有效
        if (cookie != null) {
            String ticket = cookie.getValue();
            // 校验cookie是否有值
            if (StringUtils.hasLength(ticket)) {
                // 校验redis是否有结果
                if (jedisCluster.exists(ticket)) {
                    String json = jedisCluster.get(ticket);
                    User user = ObjectMapperUtil.toObject(json, User.class);
                    // request对象将数据进行传递
                    request.setAttribute("JT_USER", user);
                    // ThreadLocal
                    UserThreadLocal.setUser(user);
                    // 已登录
                    return true;
                }
            }
            // 没有结果 cookie有误 应删除
            CookieUtil.addCookie(response,
                    JT_TICKET,
                    "",
                    "/",
                    "jt.com",
                    0);
        }
        // 数据为空 重定向系统首页
        response.sendRedirect("/user/login.html");
        return false;
    }

    // 防止内存泄露 将多余数据删除
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler, Exception ex)
            throws Exception {
        request.removeAttribute("JT_USER"); // 移除request对象
        UserThreadLocal.remove(); // 移除threadLocal数据
    }

}
